﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VM.Common.Result;
using VM.Entity.EntityMap.Member;
using VM.Entity.EntityMap.Token;
using VM.IBLL.Member;
using VM.WebCore.Jwt;
using VM.WebCore.SwaggerExtend;
using VM.Wechat;

namespace VM.WebAPI.Controllers
{
    /// <summary>
    /// sso-token鉴权 PC+PHONE
    /// </summary>
    [Route("api/token")]
    [ApiController]
    public class TokenController : ControllerBase
    {
        private readonly IJWTService _IJWTService;
        private readonly IHttpContextAccessor _HttpContextAccessor;


        public TokenController(IJWTService iJWTService, IMemberBLL iMemberBLL, IHttpContextAccessor httpContextAccessor)
        {

             
            _IJWTService = iJWTService;
            _HttpContextAccessor = httpContextAccessor;
        }
         
        /// <summary>
        /// 统一鉴权-后台接口  PC+PHONE
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        [Route("refreshtoken")]
        public async Task<ApiDataResult<MemberLoginResMap>> refreshtoken(TokenRefreshMap obj)
        {
            string Msg = "";
            JsonObject jo = await OAuthController.RefreshJwtTokenAsync(obj.RefreshKey); //RefreshJwtTokenAsync
            int expiresIn = 0;
            string tokenType = "Bearer";
            ApiDataResult<MemberLoginResMap> res = new ApiDataResult<MemberLoginResMap>();
            if (jo.code == 200)
            {
                //后端一键登录
                string accessToken = jo.token;
                res.msg = "刷新成功，状态正常";
                res.code = jo.code;
                MemberLoginResMap entity = new MemberLoginResMap()
                {
                    token_type = tokenType,
                    access_token = jo.token,
                    refresh_token = obj.RefreshKey,
                    id = _IJWTService.AnaliseToken(accessToken, "id"),
                    exp = _IJWTService.AnaliseToken(accessToken, "exp"),
                    nbf = _IJWTService.AnaliseToken(accessToken, "nbf")

                };
                //解析获取到的token
                res.data = entity;
                return res;
            }
            else
            {
                res.msg = "登录已过期，重新登录";
                res.code = 403;

            }
            return res;
        }

    }
}
